package pritace

import (
	"fmt"
	"runtime"
	"sync"
	"time"
)

func TestWg() {
	var wg sync.WaitGroup
	wg.Add(1)
	Run(&wg)
	wg.Wait()

}

func Run(wg *sync.WaitGroup) {
	fmt.Println("我跑起来了~")
	wg.Done()
}

func NoCacheChannel() {
	channel := make(chan int)
	go func() {
		for i := 0; i < 10; i++ {
			channel <- i
		}
	}()
	for i := 0; i < 10; i++ {
		fmt.Println(<-channel)
	}

}

func CacheChannel() {
	channel := make(chan int, 5)
	go func() {
		for i := 0; i < 10; i++ {
			channel <- i
		}
	}()
	for i := 0; i < 10; i++ {
		fmt.Println(<-channel)
	}
}

func ReadChannel(channel chan int) {
	var read <-chan int = channel
	for v := range read {
		fmt.Println("这是读取", v)
	}
}
func WriteChannel(channel chan int) {
	var write chan<- int = channel
	for i := 0; i < 10; i++ {
		write <- i
	}
	close(channel)
}

func SelectChannel() {
	ch1 := make(chan int, 1)
	ch2 := make(chan int, 1)
	ch3 := make(chan int, 1)
	ch1 <- 1
	ch2 <- 2
	ch3 <- 3

	//但case的条件全都满足时会随机执行其中的一个
	select {
	case <-ch1:
		fmt.Println("ch1")
	case <-ch2:
		fmt.Println("ch2")
	case <-ch3:
		fmt.Println("ch3")
	default:
		fmt.Println("没有一个满足")
	}

}

func TestGoroutine() {
	go func() {
		times := 0
		for {
			times++
			fmt.Println(times)
		}
		time.Sleep(3 * time.Second)
	}()

	var input string
	fmt.Scanln(&input)
	fmt.Println(input)

}

var counter int

func count(sy *sync.Mutex) {
	sy.Lock()
	counter++
	fmt.Println(counter)
	sy.Unlock()
}

func CheckCount() {
	lock := &sync.Mutex{}
	for i := 0; i < 10; i++ {
		go count(lock)
	}

	for {
		lock.Lock()
		c := counter
		lock.Unlock()
		runtime.Gosched()
		if c >= 10 {
			break
		}

	}
}
var (
	Count int32
	Wg sync.WaitGroup
	Mutex sync.Mutex
)
func IncCount()  {

	defer Wg.Done()
	for i := 0; i < 2; i++ {
		value := Count
		runtime.Gosched()
		value++
		Count = value
	}
}

func IncCountLock()  {

	defer Wg.Done()
	Mutex.Lock()
	{
		for i := 0; i < 2; i++ {
			value := Count
			runtime.Gosched()
			value++
			Count = value
		}
	}
	Mutex.Unlock()
}

func Printer(channel chan int) {
	for {
		value := <-channel
		if value == 0 {
			break
		}
		fmt.Println(value)
	}
	channel<-0 //我搞定啦

}

func SelectOUtTime()  {
	channel := make(chan int)
	quit := make(chan bool)
	go func() {
		for {
			select {
			case num := <-channel:
				fmt.Println(num)
			case <-time.After(3*time.Second):
				fmt.Println("超时")
				quit<- true
			default:
				fmt.Println("错误")
			}
		}

	}()

	for i := 0; i < 5; i++ {
		channel<- i
		time.Sleep(time.Second)
	}
	<-quit
	fmt.Println("程序结束")


}